import 'package:flutter/material.dart';
import 'package:provide/provide.dart';
import 'package:shop_project/model/category.dart';
import 'package:shop_project/model/category_goods_list.dart';
import 'package:shop_project/provide/child_category.dart';
import 'package:shop_project/provide/category_goods_list_provide.dart';
import 'dart:convert';
import '../config/service_method.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('商品分类'),
      ),
      body: Row(
        children: <Widget>[
          LeftCategoryNav(),
          Column(
            children: <Widget>[RightCategoryNav(), CategoryGoodsList()],
          )
        ],
      ),
    );
  }
}

//左侧导航栏
class LeftCategoryNav extends StatefulWidget {
  @override
  _LeftCategoryNavState createState() => _LeftCategoryNavState();
}

class _LeftCategoryNavState extends State<LeftCategoryNav> {
  List<CategoryItemInfo> list = [];
  var checkIndex = 0;

  @override
  void initState() {
    super.initState();
    _getCategory();
    _getGoodList();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(160),
      decoration: BoxDecoration(
          border: Border(right: BorderSide(color: Colors.black12, width: 1))),
      child: ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index) {
          return _itemInkWell(index);
        },
      ),
    );
  }

  void _getCategory() async {
    await postRequest('getCategory').then((onValue) {
      var data = json.decode(onValue.toString());
      CategoryInfo info = CategoryInfo.fromJson(data['data']);
      setState(() {
        list = info.data;
      });
      Provide.value<ChildCategory>(context)
          .setChildCategory(list[0].bxMallSubDto, list[0].mallCategoryId);
    });
  }

  void _getGoodList({String categoryId}) async {
    var formData = {
      'categoryId': categoryId == null ? '4' : categoryId,
      'categorySubId': "",
      'page': 1
    };
    await postRequest('getMallGoods', data: formData).then((onValue) {
      CategoryGoodsListModel goodsList =
          CategoryGoodsListModel.fromJson(json.decode(onValue.toString()));
      Provide.value<CategoryGoodsListProvide>(context)
          .setCategoryGoodsList(goodsList.data);
    });
  }

  Widget _itemInkWell(int index) {
    bool isClick = false;
    isClick = (index == checkIndex);
    return InkWell(
      onTap: () {
        setState(() {
          checkIndex = index;
        });
        Provide.value<ChildCategory>(context).setChildCategory(
            list[index].bxMallSubDto, list[index].mallCategoryId);
        _getGoodList(categoryId: list[index].mallCategoryId);
      },
      child: Container(
        height: ScreenUtil().setHeight(80),
        padding: EdgeInsets.only(left: 10),
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
            color: (isClick) ? Color.fromRGBO(240, 240, 240, 1) : Colors.white,
            border:
                Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Text(
          list[index].mallCategoryName,
          style: TextStyle(fontSize: ScreenUtil().setSp(26)),
        ),
      ),
    );
  }
}

//右侧top导航
class RightCategoryNav extends StatefulWidget {
  @override
  _RightCategoryNavState createState() => _RightCategoryNavState();
}

class _RightCategoryNavState extends State<RightCategoryNav> {
  @override
  Widget build(BuildContext context) {
    return Provide<ChildCategory>(
      builder: (context, child, childCategory) {
        return Container(
          height: ScreenUtil().setHeight(80),
          width: ScreenUtil().setWidth(590),
          decoration: BoxDecoration(
              color: Colors.white,
              border:
                  Border(bottom: BorderSide(color: Colors.black12, width: 1))),
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: childCategory.childCategoryList.length,
            itemBuilder: (context, index) {
              return _topItemInkWell(
                  index, childCategory.childCategoryList[index]);
            },
          ),
        );
      },
    );
  }

  void _getGoodList(String sId) async {
    var formData = {
      'categoryId': Provide.value<ChildCategory>(context).categoryId,
      'categorySubId': sId,
      'page': 1
    };
    await postRequest('getMallGoods', data: formData).then((onValue) {
      CategoryGoodsListModel goodsList =
          CategoryGoodsListModel.fromJson(json.decode(onValue.toString()));
      if (goodsList.data == null) {
        Provide.value<CategoryGoodsListProvide>(context)
            .setCategoryGoodsList([]);
      } else {
        Provide.value<CategoryGoodsListProvide>(context)
            .setCategoryGoodsList(goodsList.data);
      }
    });
  }

  Widget _topItemInkWell(int index, BxMallSubDto item) {
    bool isClick = (index == Provide.value<ChildCategory>(context).childIndex);

    return InkWell(
      onTap: () {
        Provide.value<ChildCategory>(context)
            .changeChildIndex(index, item.mallSubId);
        _getGoodList(item.mallSubId);
      },
      child: Container(
        alignment: Alignment.center,
        padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
        child: Text(item.mallSubName,
            style: TextStyle(
                fontSize: ScreenUtil().setSp(28),
                color: (isClick) ? Colors.pink : null)),
      ),
    );
  }
}

//右侧商品列表
class CategoryGoodsList extends StatefulWidget {
  @override
  _CategoryGoodsListState createState() => _CategoryGoodsListState();
}

class _CategoryGoodsListState extends State<CategoryGoodsList> {
  GlobalKey<RefreshFooterState> _footerKey = GlobalKey<RefreshFooterState>();
  @override
  Widget build(BuildContext context) {
    var scrollController = ScrollController();
    return Provide<CategoryGoodsListProvide>(
      builder: (context, child, data) {
        try {
          if (Provide.value<ChildCategory>(context).pageIndex == 1) {
            scrollController.jumpTo(0.0);
          }
        } catch (e) {
          print('进入页面第一次初始化：${e}');
        }
        if (data.categoryGoodsList.length == 0) {
          return Center(
            child: Text('暂无数据'),
          );
        } else {
          return Expanded(
              child: Container(
            width: ScreenUtil().setWidth(570),
            child: EasyRefresh(
              refreshFooter: ClassicsFooter(
                key: _footerKey,
                bgColor: Colors.white,
                textColor: Colors.pink,
                moreInfoColor: Colors.pink,
                showMore: true,
                noMoreText: Provide.value<ChildCategory>(context).noMoreText,
                moreInfo: '...',
                loadedText: '加载完毕',
                loadingText: '加载中',
                loadReadyText: '',
                loadText: '上拉加载...',
              ),
              child: ListView.builder(
                controller: scrollController,
                itemCount: data.categoryGoodsList.length,
                itemBuilder: (context, index) {
                  return _listWidget(data.categoryGoodsList, index);
                },
              ),
              loadMore: () async {
                _getMoreGoodList();
              },
            ),
          ));
        }
      },
    );
  }

  Widget _goodsImage(List<CategoryGoodsInfo> list, int index) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(list[index].image),
    );
  }

  Widget _goodsName(List<CategoryGoodsInfo> list, int index) {
    return Container(
      padding: EdgeInsets.all(5.0),
      width: ScreenUtil().setWidth(370),
      child: Text(
        list[index].goodsName,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
      ),
    );
  }

  Widget _goodsPrice(List<CategoryGoodsInfo> list, int index) {
    return Container(
      margin: EdgeInsets.only(top: 20.0),
      width: ScreenUtil().setWidth(370),
      child: Row(
        children: <Widget>[
          Text(
            '价格：${list[index].presentPrice}',
            style:
                TextStyle(color: Colors.pink, fontSize: ScreenUtil().setSp(30)),
          ),
          Text(
            '￥${list[index].oriPrice}',
            style: TextStyle(
                color: Colors.black26, decoration: TextDecoration.lineThrough),
          )
        ],
      ),
    );
  }

  Widget _listWidget(List<CategoryGoodsInfo> list, int index) {
    return InkWell(
      onTap: () {},
      child: Container(
        padding: EdgeInsets.only(top: 5, bottom: 5),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Row(
          children: <Widget>[
            _goodsImage(list, index),
            Column(
              children: <Widget>[
                _goodsName(list, index),
                _goodsPrice(list, index)
              ],
            )
          ],
        ),
      ),
    );
  }

  void _getMoreGoodList() async {
    Provide.value<ChildCategory>(context).addPageIndex();
    var formData = {
      'categoryId': Provide.value<ChildCategory>(context).categoryId,
      'categorySubId': Provide.value<ChildCategory>(context).subId,
      'page': Provide.value<ChildCategory>(context).pageIndex
    };
    await postRequest('getMallGoods', data: formData).then((onValue) {
      CategoryGoodsListModel goodsList =
          CategoryGoodsListModel.fromJson(json.decode(onValue.toString()));
      if (goodsList.data == null) {
        Provide.value<ChildCategory>(context).changeNoMore('没有更多了');
        Fluttertoast.showToast(
            msg: '没有更多了',
            gravity: ToastGravity.BOTTOM,
            timeInSecForIos: 1,
            backgroundColor: Colors.pink,
            textColor: Colors.white,
            fontSize: 16);
      } else {
        Provide.value<CategoryGoodsListProvide>(context)
            .addCategoryGoodsList(goodsList.data);
      }
    });
  }
}
